const bcrypt = require('bcryptjs');

const {
  userExistsErr,
  userRegisterErr,
  userNotRegisterErr,
  userPasswordMatchErr,
  userLoginErr,
} = require('@constant/error.type');

const { validIncorrectParameter } = require('@utils/tools');

const { userRegisterSchema, userChangePwdSchema } = require('./user.schema');

const { userGet } = require('./user.service');

module.exports = {
  // 账号密码验证
  async userRegisterValidator(ctx, next) {
    const valid = validIncorrectParameter(userRegisterSchema, ctx);

    !valid && (await next());
  },

  async changePwdValidator(ctx, next) {
    const valid = validIncorrectParameter(userChangePwdSchema, ctx);

    !valid && (await next());
  },

  // 注册数据库验证
  async verifyRegister(ctx, next) {
    const { user_name } = ctx.request.body;

    // 用户名唯一判断
    try {
      const res = await userGet({ user_name });

      if (res) {
        return ctx.app.emit('error', userExistsErr, ctx);
      }
    } catch (err) {
      return ctx.app.emit('error', userRegisterErr, ctx);
    }

    await next();
  },

  // 登录数据库验证
  async verifyLogin(ctx, next) {
    const { user_name, password } = ctx.request.body;

    // 用户名唯一判断
    try {
      const res = await userGet({ user_name });

      if (!res) {
        return ctx.app.emit('error', userNotRegisterErr, ctx);
      }

      const matchPwd = bcrypt.compareSync(password, res.password);

      if (!matchPwd) {
        return ctx.app.emit('error', userPasswordMatchErr, ctx);
      }
    } catch (err) {
      return ctx.app.emit('error', userLoginErr, ctx);
    }

    await next();
  },

  // 密码加密
  async crpytPassword(ctx, next) {
    const { password } = ctx.request.body;

    const salt = bcrypt.genSaltSync(10);

    const hash = bcrypt.hashSync(password, salt);

    ctx.request.body.password = hash;
    console.log('123');

    await next();
  },
};
